<script setup>
import {
    Edit,
    Delete,
    Plus,
    Search,
    Refresh,
    View,
    Check,
    Close
} from '@element-plus/icons-vue'

import { ref } from 'vue'
import { formatDate } from '@/utils/format.js'

//供应商数据模型
const vendor = ref([])

//分页条数据模型
const pageNum = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(3)//每页条数
const searchForm = ref({})

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    pageSize.value = size
    getVendorList()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    pageNum.value = num
    getVendorList()
}

const visibleDrawer = ref(false)
const vendorModel = ref({})
const title = ref('')
const vendorName = ref('')
//查询供应商列表
import { getVendorListPageService, addVendorService, updateVendorService, deleteVendorService } from '@/api/vendor.js'
const getVendorList = async () => {
    let res = await getVendorListPageService({
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        vendorName: vendorName.value ? vendorName.value : null
    })
    vendor.value = res.data.items
    total.value = res.data.total
}
getVendorList()

//添加供应商
import { ElMessage } from 'element-plus'
const addVendor = async () => {
    let res = await addVendorService(vendorModel.value)
    ElMessage.success(res.message ? res.message : '添加成功')
    visibleDrawer.value = false
    getVendorList()
}
//清空供应商表单
const clearVendor = () => {
    vendorModel.value = {}
}
//回显供应商信息
const editVendor = (row) => {
    //深拷贝
    vendorModel.value = JSON.parse(JSON.stringify(row))
    title.value = '编辑供应商'
    visibleDrawer.value = true
}
//更新供应商
const updateVendor = async () => {
    let res = await updateVendorService(vendorModel.value)
    ElMessage.success(res.msg ? res.msg : '更新成功')
    visibleDrawer.value = false
    getVendorList()
}
//删除供应商
import { ElMessageBox } from 'element-plus'
const deleteVendor = async (id) => {
    ElMessageBox.confirm(
        '你确定要删除该供应商信息么?',
        '温馨提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            draggable: true,
        }
    )
        .then(async () => {
            let res = await deleteVendorService(id)
            if (res.code == 0) {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
                getVendorList()
                return
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消删除',
            })
        })
}

// 富文本编辑器
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, shallowRef } from "vue";
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { useTokenStore } from '@/stores/token.js'


const tokenStore = useTokenStore()
/* wangEditor5 初始化开始 */
const editorRef = shallowRef()  // 编辑器实例，必须用 shallowRef
const mode = 'default'
const editorConfig = { MENU_CONF: {} }
// 图片上传配置
editorConfig.MENU_CONF['uploadImage'] = {
    headers: {
        'Authorization': tokenStore.token,
    },
    server: '/api/wang/upload',  // 服务端图片上传接口
    fieldName: 'file'  // 服务端图片上传接口参数
}
// 组件销毁时，也及时销毁编辑器，否则可能会造成内存泄漏
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})
// 记录 editor 实例，重要！
const handleCreated = (editor) => {
    editorRef.value = editor
}
/* wangEditor5 初始化结束 */

// 弹框定义
const viewVisible = ref(false)
const vendorTitle = ref('')
const viewContent = ref('')
const showInfo = (row) => {
    viewVisible.value = true
    vendorTitle.value = row.vendorName
    viewContent.value = row.description
}

// 批量删除
import { deleteVendorBatchService } from '@/api/vendor.js'
const ids = ref([])
const handleSelectionChange = (rows) => {
    ids.value = rows.map(v => v.id)
    console.log(ids.value);
}
const batchDeleteVendor = async () => {
    ElMessageBox.confirm(
        '你确定要删除选中的供应商么?',
        '温馨提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            draggable: true,
        }
    )
        .then(async () => {
            let res = await deleteVendorBatchService(ids.value)
            if (res.code == 0) {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
                getVendorList()
                return
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消删除',
            })
        })
}
</script>
<template>
    <div class="vendor-container">
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    <span class="title">供应商管理</span>
                    <div class="header-actions">
                        <el-button type="primary" @click="visibleDrawer = true, title = '添加供应商', clearVendor()" class="add-button">
                            <el-icon><Plus /></el-icon>添加供应商
                        </el-button>
                        <el-button type="danger" @click="batchDeleteVendor" class="delete-button">
                            <el-icon><Delete /></el-icon>批量删除
                        </el-button>
                    </div>
                </div>
            </template>
            
            <!-- 搜索区域 -->
            <div class="search-area">
                <el-form :inline="true" :model="searchForm" class="demo-form-inline">
                    <el-form-item label="供应商名称">
                        <el-input 
                            v-model="vendorName" 
                            placeholder="请输入供应商名称" 
                            clearable 
                            prefix-icon="Search"
                            class="custom-input"
                        />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="getVendorList" class="search-button">
                            <el-icon><Search /></el-icon>搜索
                        </el-button>
                        <el-button @click="vendorName = '', getVendorList" class="reset-button">
                            <el-icon><Refresh /></el-icon>重置
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 供应商列表 -->
            <el-table 
                :data="vendor" 
                style="width: 100%" 
                border 
                stripe
                @selection-change="handleSelectionChange"
                :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
                :row-style="{ height: '60px' }"
                :cell-style="{ padding: '8px 0' }"
                highlight-current-row>
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="供应商名称" prop="vendorName" min-width="180" align="center" show-overflow-tooltip />
                <el-table-column label="联系电话" prop="phone" min-width="140" align="center" />
                <el-table-column label="详细描述" min-width="180" align="center">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="showInfo(row)" class="view-button">
                            <el-icon><View /></el-icon>查看详情
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column label="更新时间" prop="updateTime" min-width="180" align="center" show-overflow-tooltip>
                    <template #default="{ row }">
                        {{ formatDate(row.updateTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" min-width="120" align="center" fixed="right">
                    <template #default="{ row }">
                        <div class="operation-buttons">
                            <el-tooltip content="编辑" placement="top">
                                <el-button :icon="Edit" circle type="primary" @click="editVendor(row)" size="small" />
                            </el-tooltip>
                            <el-tooltip content="删除" placement="top">
                                <el-button :icon="Delete" circle type="danger" @click="deleteVendor(row.id)" size="small" />
                            </el-tooltip>
                        </div>
                    </template>
                </el-table-column>
                <template #empty>
                    <el-empty description="暂无供应商数据" />
                </template>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination
                    v-model:current-page="pageNum"
                    v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="total"
                    layout="total, sizes, prev, pager, next, jumper"
                    background
                    @size-change="onSizeChange"
                    @current-change="onCurrentChange"
                />
            </div>
        </el-card>

        <!-- 抽屉 -->
        <el-drawer 
            v-model="visibleDrawer" 
            :title="title" 
            direction="rtl" 
            size="50%"
            :before-close="() => visibleDrawer = false"
            destroy-on-close
            :show-close="false"
            class="custom-drawer">
            <template #header>
                <div class="drawer-header">
                    <div class="drawer-title">
                        <el-icon class="title-icon"><component :is="title === '添加供应商' ? Plus : Edit" /></el-icon>
                        <span>{{ title }}</span>
                    </div>
                    <el-button class="close-button" @click="visibleDrawer = false" circle>
                        <el-icon><Close /></el-icon>
                    </el-button>
                </div>
            </template>
            <div class="drawer-content">
                <el-form :model="vendorModel" label-width="100px" class="drawer-form">
                    <el-form-item label="供应商名称">
                        <el-input 
                            v-model="vendorModel.vendorName" 
                            placeholder="请输入供应商名称" 
                            class="custom-input"
                            prefix-icon="User"
                        />
                    </el-form-item>
                    <el-form-item label="电话号码">
                        <el-input 
                            v-model="vendorModel.phone" 
                            placeholder="请输入电话号码" 
                            class="custom-input"
                            prefix-icon="Phone"
                        />
                    </el-form-item>
                    <el-form-item label="详情描述">
                        <div class="editor-container">
                            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :mode="mode" />
                            <Editor 
                                style="height: 500px; overflow-y: hidden;" 
                                v-model="vendorModel.description" 
                                :mode="mode"
                                :defaultConfig="editorConfig" 
                                @onCreated="handleCreated" 
                            />
                        </div>
                    </el-form-item>
                    <el-form-item class="drawer-footer">
                        <el-button type="primary" @click="title === '添加供应商' ? addVendor() : updateVendor()" class="submit-button">
                            <el-icon><Check /></el-icon>提交
                        </el-button>
                        <el-button @click="visibleDrawer = false" class="cancel-button">
                            <el-icon><Close /></el-icon>取消
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-drawer>

        <!-- 详情弹框 -->
        <el-dialog 
            v-model="viewVisible" 
            width="60%" 
            destroy-on-close
            class="custom-dialog"
            :show-close="false">
            <template #header>
                <div class="dialog-header">
                    <div class="dialog-title">
                        <el-icon class="title-icon"><View /></el-icon>
                        <span>{{ vendorTitle }}</span>
                    </div>
                    <el-button class="close-button" @click="viewVisible = false" circle>
                        <el-icon><Close /></el-icon>
                    </el-button>
                </div>
            </template>
            <div class="dialog-content-wrapper">
                <div class="dialog-content" v-html="viewContent"></div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="viewVisible = false" class="close-dialog-button">
                        <el-icon><Close /></el-icon>关闭
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<style lang="scss" scoped>
.vendor-container {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: 100vh;

    .box-card {
        border-radius: 8px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        transition: all 0.3s;

        &:hover {
            box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
        }
    }

    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 10px;

        .title {
            font-size: 20px;
            font-weight: bold;
            color: #303133;
            position: relative;
            padding-left: 12px;
            
            &::before {
                content: '';
                position: absolute;
                left: 0;
                top: 50%;
                transform: translateY(-50%);
                width: 4px;
                height: 20px;
                background: linear-gradient(to bottom, #1976d2, #42a5f5);
                border-radius: 2px;
            }
        }

        .header-actions {
            display: flex;
            gap: 12px;
            
            .add-button {
                background: linear-gradient(to right, #1976d2, #42a5f5);
                border: none;
                padding: 10px 20px;
                transition: all 0.3s;
                
                &:hover {
                    transform: translateY(-2px);
                    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
                }
            }
            
            .delete-button {
                background: linear-gradient(to right, #f56c6c, #f78989);
                border: none;
                padding: 10px 20px;
                transition: all 0.3s;
                
                &:hover {
                    transform: translateY(-2px);
                    box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
                }
            }
        }
    }

    .search-area {
        margin-bottom: 20px;
        padding: 20px;
        background-color: #ffffff;
        border-radius: 8px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);

        .demo-form-inline {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            align-items: center;
        }

        .custom-input {
            width: 240px;
            
            :deep(.el-input__wrapper) {
                box-shadow: 0 0 0 1px #dcdfe6 inset;
                border-radius: 4px;
                transition: all 0.3s;
                
                &:hover, &.is-focus {
                    box-shadow: 0 0 0 1px #409eff inset;
                }
            }
        }

        .search-button {
            background: linear-gradient(to right, #1976d2, #42a5f5);
            border: none;
            padding: 10px 20px;
            transition: all 0.3s;
            
            &:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
            }
        }
        
        .reset-button {
            border: 1px solid #dcdfe6;
            padding: 10px 20px;
            transition: all 0.3s;
            
            &:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
                border-color: #c0c4cc;
            }
        }
    }

    .pagination-container {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
    }

    .operation-buttons {
        display: flex;
        justify-content: center;
        gap: 8px;
    }

    .view-button {
        transition: all 0.3s;
        
        &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
        }
    }
}

// 抽屉样式
.custom-drawer {
    :deep(.el-drawer__header) {
        margin-bottom: 0;
        padding: 0;
        border-bottom: 1px solid #ebeef5;
    }

    .drawer-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px 20px;
        background: linear-gradient(to right, #1976d2, #42a5f5);
        
        .drawer-title {
            display: flex;
            align-items: center;
            gap: 10px;
            
            .title-icon {
                font-size: 20px;
                color: white;
            }
            
            span {
                font-size: 18px;
                font-weight: bold;
                color: white;
            }
        }
        
        .close-button {
            background: rgba(255, 255, 255, 0.2);
            border: none;
            color: white;
            transition: all 0.3s;
            
            &:hover {
                background: rgba(255, 255, 255, 0.3);
                transform: rotate(90deg);
            }
        }
    }

    .drawer-content {
        padding: 30px;
    }

    .drawer-form {
        .custom-input {
            :deep(.el-input__wrapper) {
                box-shadow: 0 0 0 1px #dcdfe6 inset;
                border-radius: 4px;
                transition: all 0.3s;
                
                &:hover, &.is-focus {
                    box-shadow: 0 0 0 1px #409eff inset;
                }
            }
        }

        .editor-container {
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            overflow: hidden;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
            transition: all 0.3s;
            
            &:hover {
                box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
            }
        }

        .drawer-footer {
            margin-top: 40px;
            display: flex;
            justify-content: center;
            gap: 20px;

            .submit-button, .cancel-button {
                min-width: 120px;
                padding: 12px 24px;
                transition: all 0.3s;
                border-radius: 4px;
                
                &:hover {
                    transform: translateY(-2px);
                }
            }

            .submit-button {
                background: linear-gradient(to right, #1976d2, #42a5f5);
                border: none;
                
                &:hover {
                    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
                }
            }
            
            .cancel-button {
                &:hover {
                    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
                }
            }
        }
    }
}

// 弹框样式
.custom-dialog {
    :deep(.el-dialog__header) {
        padding: 0;
        margin: 0;
    }
    
    :deep(.el-dialog__body) {
        padding: 0;
    }
    
    :deep(.el-dialog__footer) {
        padding: 16px 20px;
        border-top: 1px solid #ebeef5;
        background-color: #f5f7fa;
    }
    
    .dialog-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px 20px;
        background: linear-gradient(to right, #1976d2, #42a5f5);
        
        .dialog-title {
            display: flex;
            align-items: center;
            gap: 10px;
            
            .title-icon {
                font-size: 20px;
                color: white;
            }
            
            span {
                font-size: 18px;
                font-weight: bold;
                color: white;
            }
        }
        
        .close-button {
            background: rgba(255, 255, 255, 0.2);
            border: none;
            color: white;
            transition: all 0.3s;
            
            &:hover {
                background: rgba(255, 255, 255, 0.3);
                transform: rotate(90deg);
            }
        }
    }

    .dialog-content-wrapper {
        padding: 30px;
        background-color: #ffffff;
    }
    
    .dialog-content {
        padding: 20px;
        max-height: 60vh;
        overflow-y: auto;
        background-color: #f9f9f9;
        border-radius: 8px;
        box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.05);
        line-height: 1.8;
        
        :deep(img) {
            max-width: 100%;
            border-radius: 4px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
        
        :deep(p) {
            margin-bottom: 16px;
        }
        
        :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
            margin-top: 24px;
            margin-bottom: 16px;
            color: #303133;
        }
        
        :deep(table) {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 16px;
            
            th, td {
                border: 1px solid #dcdfe6;
                padding: 8px 12px;
            }
            
            th {
                background-color: #f5f7fa;
            }
        }
    }
    
    .dialog-footer {
        display: flex;
        justify-content: center;
        
        .close-dialog-button {
            min-width: 120px;
            padding: 12px 24px;
            transition: all 0.3s;
            border-radius: 4px;
            
            &:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            }
        }
    }
}
</style>